package com.atguigu.alice;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author alice
 * @date 2021/10/28
 * @apiNote
 */
public class FileChannelAccept {
    public static final String GREETING = "HELLO LUYT.\r\n";

    public static void main(String[] args) throws IOException, InterruptedException {
        int port = 1234;
        if (args.length>0){
            port = Integer.parseInt(args[0]);
        }
        ByteBuffer buffer = ByteBuffer.wrap(GREETING.getBytes());
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        socketChannel.socket().bind(new InetSocketAddress(port));
        socketChannel.configureBlocking(false);
        while (true){
            System.out.println("waiting for connections");
            SocketChannel accept = socketChannel.accept();
            if(accept==null){
                System.out.println("null");
                Thread.sleep(2000);
            }else {
                System.out.println("incoming connection from:"+accept.socket().getRemoteSocketAddress());
                buffer.rewind();
                accept.write(buffer);
                accept.close();
            }
        }
    }
}
